<?php

use App\Annotations\LoginRequired;
use App\Aop\Auth;
use App\Aop\RequestInit;
use App\Aop\RequestValid;
use Monolog\Handler\RotatingFileHandler;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Ray\Aop\Pointcut;
use Ray\Aop\Matcher;
use Wonfu\Core\Annotations\RequestMapping;
use Wonfu\Core\Annotations\Valid;
use Monolog\Handler\StreamHandler;
use Psr\Container\ContainerInterface;
use Noodlehaus\Config;
use Wonfu\Core\AppConfig;
use Wonfu\Http\ServerRequest;
use Wonfu\HttpClient\Client;
use Ray\Aop\PriorityPointcut;
use App\HttpClientAfterHandler;

$hllEnv = get_cfg_var('hll.env');
$stgEnv = get_cfg_var('hll_stg_env');
if (!$hllEnv) {
    $hllEnv = 'dev';  //默认是dev
}
define('HLL_ENV', strtolower($hllEnv)); //dev/stg/prd
define('HLL_STG_ENV', strtolower($stgEnv));
//$hllEnv = 'prd';
define('HLL_IS_DEV', $hllEnv == 'dev'); //是否是开发环境
define('HLL_IS_STG', $hllEnv == 'stg'); //是否是STG环境
define('HLL_IS_PRD', $hllEnv == 'prd'); //是否是PRD环境
define('SERVICE_APPID', 'wonfu-acme');
define('LOG_BASE', '/home/data/logs/');

// dms资源服务初始化
return [
    // Bind an interface to an implementation
    'env' => get_cfg_var('hll.env'),
    Config::class => function (ContainerInterface $c) {
        $env = $c->get('env') ?: 'test';
        $config = new Config([CONFIG_DIR . '/app.yaml', '?' . CONFIG_DIR . '/app-' . $env . '.yaml']);
        if ($env == 'test') {
            define('LOG_BASE_DEV', $config->get('log.path') . '/logs/');
        } else {
            define('LOG_BASE_DEV', $_SERVER['HOME'] . '/logs/');
        }
        return $config;
    },
    // Configure Twig
    Environment::class => function () {
        $loader = new FilesystemLoader(SRC_DIR . '/Views');
        return new Environment($loader);
    },
    // PointCut
    'pointCut' => [
        new PriorityPointcut(
            (new Matcher())->any(),
            (new Matcher())->annotatedWith(RequestMapping::class),
            [(new RequestInit())]
        ),
        new Pointcut((new Matcher())->any(),
            (new Matcher())->annotatedWith(LoginRequired::class),
            [(new Auth())]),
        new Pointcut(
            (new Matcher())->any(),
            (new Matcher())->annotatedWith(Valid::class),
            [new RequestValid()]),

    ],
    // logger
    Psr\Log\LoggerInterface::class => function (ContainerInterface $c) {
        $env = $c->get('env') ?: 'test';
        /** @var ServerRequest $request */
        $request = $c->get(ServerRequest::class);
        $name = sprintf('%s-%s', $request->getUniqReqNo(), $request->getController() . '.' . $request->getAction());
        // Create the logger
        $logger = new \App\Core\MallLogger(SERVICE_APPID);
        $logger->setHandlerAction($name);
        $logger->setTraceNo($request->getUniqReqNo());
        $logBase = TMP_DIR;
        if (PHP_SAPI == 'cgi' || PHP_SAPI == 'fpm-fcgi') {
            $logBase = LOG_BASE . $_SERVER['HTTP_HOST'];
        } elseif (PHP_SAPI == 'cli') {
            $logBase = HLL_IS_DEV ? LOG_BASE_DEV : LOG_BASE;
            $domain = $c->get(Config::class)->get('domain');
            $logBase = $logBase . $domain;
        }
        $handler = new RotatingFileHandler($logBase . '/app.log');
        $logger->pushHandler($handler);
        // Now add some handlers
        return $logger;
    },
    Client::class => function (ContainerInterface $c) {
        $client = new Client();
        $clientHandler = new HttpClientAfterHandler();
        $c->injectOn($clientHandler);
        $client->setAfterHandler($clientHandler);
        return $client;
    },
    'appConfig' => function () {
        $appConfig = new AppConfig();
        $appConfig->setTmpDir(TMP_DIR);
        $appConfig->setControllerDir(SRC_DIR . '/Controller');
        $appConfig->setRootDir(ROOT_DIR);
        return $appConfig;
    },
    RedisCluster::class => function () {
        $redis =  new Redis();
        $redis->connect('127.0.0.1');
        return $redis;
    }
];